package com.entrogy.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.entrogy.bean.StudentEntity;
import com.entrogy.bean.StudentIcEntity;
import com.entrogy.service.StudentService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class StudentIcCardExcelListener extends AnalysisEventListener<StudentIcEntity> {

    private StudentService studentService;

    private Logger logger = LoggerFactory.getLogger(StudentIcCardExcelListener.class);

    private List<StudentEntity> studentIcCardList = new ArrayList<>();

    private List<StudentEntity> failBindStudentList = new ArrayList<>();

    public StudentIcCardExcelListener(){}

    public StudentIcCardExcelListener(StudentService studentService){
        this.studentService = studentService;
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        logger.info("表头：{}", JSON.toJSONString(headMap));
    }

    @Override
    public void invoke(StudentIcEntity studentIcEntity, AnalysisContext context) {
        logger.info(studentIcEntity.toString());
        StudentEntity studentEntity = new StudentEntity();
        studentEntity.setId(studentIcEntity.getStudentId());
        studentEntity.setIcNumber(studentIcEntity.getIcCardNumber());
        if (studentEntity.getId() != 0 && StringUtils.isNoneBlank(studentEntity.getIcNumber())){
            studentIcCardList.add(studentEntity);
        }
    }

    // 整个excel解析结束会执行doAfterAllAnalysed()方法
    public void doAfterAllAnalysed(AnalysisContext context) {
        for (StudentEntity studentEntity : studentIcCardList) {
            logger.info("当前导入的学生IC卡数据" + studentEntity.getStudentName());
            // 绑定该张IC卡时，需要判断该IC卡是否已经绑定
            List<StudentEntity> studentFormDbByIcCard = studentService.listSchoolAllStudent(null, null, null, null, null, studentEntity.getIcNumber(), null);
            if (studentFormDbByIcCard.size() > 0){
                logger.error("批量绑定IC卡信息的时候，IC卡号为=>" + studentEntity.getIcNumber() + "重复绑定！，该生" + studentEntity.getId() + "绑定失败！");
                failBindStudentList.add(studentEntity);
                continue;
            }
            studentService.updateStudent(studentEntity);
        }
        this.studentIcCardList.clear();
    }

    public List<StudentEntity> getFailBindStudentList() {
        return failBindStudentList;
    }

    public void setFailBindStudentList(List<StudentEntity> failBindStudentList) {
        this.failBindStudentList = failBindStudentList;
    }
}
